package com.rabbitmq.demo.producer;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RabbitMQTopicExchangeProducer {
    private static String host = "127.0.0.1";
    private static String userName = "guest";
    private static String passWord = "guest";
    private static int port = 5672;
    private static final  String ExchangeName = "topicOne";
    private static String routingKey = "com.mq.rabbit.error";
    /**
     * @param args
     */
    public static void main(String[] args) {

        try {
            //1、连接到RabbitMQ服务器
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(host);
            factory.setPort(port);
            factory.setUsername(userName);
            factory.setPassword(passWord);
            Connection connect = factory.newConnection();
            Channel channel = connect.createChannel();
            //2、声明交换机
            channel.exchangeDeclare(ExchangeName, "topic"); // 声明topic交换器
            //3、发送消息到name为ExchangeName的交换机并设置消息的路由关键字routingKey
            String message = "topic 时间：" + System.currentTimeMillis();
            channel.basicPublish(ExchangeName, routingKey, null, message.getBytes("UTF-8"));
            channel.close();
            connect.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
